<template>
  <view class="container">
    <view class="top_map">
      <map style="width: 100%; height: 50vh;" :polyline="polyline" id="map" class="map" :latitude="latitude" :longitude="longitude" :max-scale="16" :markers="markers" :show-location="true"></map>
    </view>
    <view class="operate">
      <view class="operate_top">
        <view>开始巡检</view>
      </view>
      <view class="operate_bot">
        <view class="operate_list">
          <view class="operate_list_title">开始时间</view>
          <view class="operate_list_info">{{ currentTime }}</view>
        </view>
        <view class="operate_list">
          <view class="operate_list_title">里程（KM）</view>
          <view class="operate_list_info">{{ distanceNum }}</view>
        </view>
        <view class="operate_list">
          <view class="operate_list_title">巡查时长</view>
          <view class="operate_list_info">{{ Nowtime }}</view>
        </view>
        <view class="operate_list">
          <view class="operate_list_title">未检查</view>
          <view class="operate_list_info">{{ notChecked || '0' }}</view>
        </view>
        <view class="operate_list">
          <view class="operate_list_title">已检查</view>
          <view class="operate_list_info">{{ checked || '0' }}</view>
        </view>
        <view class="operate_list">
          <view class="operate_list_title">发现问题</view>
          <view class="operate_list_info">{{ problems || '0' }}</view>
        </view>
      </view>
      <view class="operate_tips">
        <view>今日：{{ currentDate }}&nbsp;&nbsp;当前：{{ pagedata.floodSeason }}&nbsp;&nbsp;频次：{{ pagedata.frequency }}次/天</view>
      </view>
      <view class="operate_btn">
        <view @click="startTime" v-if="startBtn" class="operateBtn">
          <view>开始巡查</view>
        </view>
        <view @click="stopTime" v-else class="operateBtn stop">
          <view>结束巡查</view>
        </view>
        <view @click="toPage" class="operateBtn">
          <view>检查详情</view>
        </view>
      </view>
      <view @click="backPage" class="backbtn">
        <image src="/static/images/back.png" />
      </view>
    </view>
  </view>
</template>

<script>
  import dayjs from "../../utlis/dayjs.min";
  var set; // 计时定时器
	var line;  // 路线定时器

  export default {
    name: 'inspection',
    data() {
      return {
        pagedata: {},
        latitude: 37.3628,
				longitude: 122.355099,
				markers: [],//标记点
				// polyline: [],//路线
        startBtn: true,
        numList: [], // 巡查距离
				distanceNum: 0, // 巡查距离总和
				numid: 1, // markers id
        xcPath: [], //现在的巡查路线
				xcEnd: null,//结束时间
        Nowtime: "未开始",
        // 开始时间
        currentTime: '00-00-00',
        currentDate: '00-00-00',
        realTime: '',
        // 连线
				polyline: [{
					points: [],
					width: 8,
					color: '#000000AA',
					borderWidth: 3,
				}],
        notChecked: '0',
        checked: '0',
        problems: '0',
        patrolinfo: {},
        baseinfo: {},
      }
    },
    onLoad(options) {
      if(options) {
        this.pagedata = JSON.parse(options.data)
      }
    },
    onReady() {
      this.getCurrentLocate()
      this.currentTime = dayjs().format('MM-DD HH:mm')
      this.currentDate = dayjs().format('YYYY-MM-DD')
      this.realTime = dayjs().format('YYYY-MM-DD HH:mm:ss')

      // this.getBaseinfo(this.patrolinfo)
      // this.showpoint(this.pagedata.uuid)
    },
    onShow() {
      if(this.baseinfo.id) {
        this.updateBase(this.baseinfo)
      }
    },
    methods: {
      // 获取当前定位
			getCurrentLocate() {
				const that = this
				uni.getLocation({
					type: 'gcj02',
					// geocode: true,
					// isHighAccuracy: true,
					success: (res) => {
						that.longitude = res.longitude
						that.latitude = res.latitude;

						that.markers.push({
							id: that.numid,
							width: 100,
							height: 100,
							longitude: that.longitude,
							latitude: that.latitude,
							iconPath: '../static/position.png',
						})
					},
          fail: (err) => {
            console.log('file: index.vue:143 ~ err:', err)
          }
				})
			},
      // 显示巡查点位
      showpoint(id) {
        let that = this
        this.$request.getpointlist({ patrolReservoirId: id }).then(res => {
          let list = res.data || []
          list.forEach(v => {
            that.numid++
            that.markers.push({
              id: that.numid,
              width: 30,
              height: 30,
              longitude: Number(v.longitude),
              latitude: Number(v.latitude),
              iconPath: '../static/position2.png',
              label: {
                content: v.pointName,
                color: '#ffffff',
                fontSize: 20
              }
            })
          })
        })
      },
      // 开始巡检
      startTime() {
        this.startBtn = false
        this.Nowtime = "00,00,00"
				let time = this.Nowtime
        this.TimeConver(time)
				this.getAddress()
				this.numList = []

        this.currentTime = dayjs().format('MM-DD HH:mm')
        this.currentDate = dayjs().format('YYYY-MM-DD')
        this.realTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
        this.$request.addpatrol({ taskId: this.pagedata.uuid, time: this.realTime }).then(res => {
          let tempdata = res.data || {}
          this.patrolinfo = tempdata
          this.getBaseinfo(tempdata)
        })
      },
      // 获取巡检基本信息
      getBaseinfo(tempdata) {
        this.$request.reservoirBaseInfo({ reseId: tempdata.rese_id }).then(res => {
          let temp = res.data || {}
          this.baseinfo = temp
          this.notChecked = temp.notInspectedCount
          this.checked = temp.inspectedCount
          this.problems = temp.issueCount
        })
      },
      // 更新巡检基本信息
      updateBase(item) {
        let tempdata = {
          id: item.id,
          // distance: Number(this.distanceNum),
          // inspectionDuration: this.Nowtime,
          // notInspectedCount: this.notChecked, //未巡查数量
          // inspectedCount: this.checked,  //已巡查数量
          // issueCount: this.problems, //问题数
        }
        this.$request.updateBaseInfo(tempdata).then(res => {
          this.getBaseinfo(this.patrolinfo)
        })
      },
      // 结束巡检
      stopTime() {
        let that = this
        // if(this.notChecked != '0') {
        //   uni.showToast({
        //     title: '请检查完毕后再结束巡查',
        //     icon: 'none',
        //     duration: 2000
        //   });
        //   return
        // }
				this.xcEnd = dayjs().format('YYYY-MM-DD HH:mm:ss')

        // 上传巡查结束
        let donedata = {
          id: that.baseinfo.id,
          endTime: that.xcEnd, // 结束时间
          distance: Number(that.distanceNum), // 里程
          inspectionDuration: that.Nowtime, // 巡查时长
        }

        this.$request.doneBaseInfo(donedata).then(res => {
          if(res.code == 200) {
            clearInterval(line)//清除路线定位定时器
            clearInterval(set) //清除时间定时器
            this.toFurther()
          } else {

          }
        }).catch(err => {
          console.log('file: index.vue:251 ~ err:', err)
        })
      },
      // 其他信息提交
      toFurther() {
        let that = this
        // 上传巡查轨迹 经纬度
        let temparr = []
        this.markers.forEach(v => {
          temparr.push({ reservoirId: that.baseinfo.id, locationLongitude: v.longitude, locationLatitude: v.latitude })
        })
        this.$request.addtrack(temparr).then(res => {
          uni.showToast({
            title: '巡查结束',
            icon: 'none',
            duration: 2000
          });
          setTimeout(() => {
            uni.navigateBack({ delta: 1 })
          }, 2000);
          this.startBtn = true
        }).catch(err => {
          console.log('file: index.vue:234 ~ err:', err)
        })

        // // 上传巡查里程 时长
        // let tempdata = {
        //   id: this.baseinfo.id,
        //   endtime: this.xcEnd,
        //   distance: Number(this.distanceNum),// 里程
        //   inspectionDuration: this.Nowtime, // 时长
        //   // notInspectedCount: this.notChecked, // 未巡查数量
        //   // inspectedCount: this.checked,  // 已巡查数量
        //   // issueCount: this.problems, // 问题数
        // }
        // this.$request.updateBaseInfo(tempdata).then(res => {
        //   console.log('file: index.vue:247 ~ res:', res)
        // }).catch(err => {
        //   console.log('file: index.vue:249 ~ err:', err)
        // })
      },
      // 绘制行动轨迹
			getAddress() {
        let xcPaths = []
				line = setInterval(()=>{
					uni.getLocation({
					  type: 'gcj02',
						// isHighAccuracy: true,
					  success:(res)=> {
							if(res.accuracy != 0 && res.latitude != '5e-324') {
								this.numid++
								var lng = res.longitude;
								var lat = res.latitude;
								this.toLocation(lng, lat)
								// 巡查轨迹路线
								let newPoint = {
									longitude: lng,
									latitude: lat,
								}
								xcPaths.push(newPoint)

								this.markers.push({
									id: this.numid,
									width: 100,
									height: 100,
									longitude: newPoint.longitude,
									latitude: newPoint.latitude,
									iconPath: '/pagesA/static/taskPoint.png',
								})
								// 路线
								let nowLine = {
									points: xcPaths, //路线数组
									color: '#000000AA', //线的颜色
									width: 10, //线的宽度
									borderWidth: 2, //线的厚度
									// borderColor: '#ff0000', //线的边框颜色
									dottedLine: false, //是否虚线
									arrowLine: false //带箭头的线 开发者工具暂不支持该属性
								}
                this.polyline[0].points = this.markers
								if(this.xcPath.length > 0) {
									this.polyline[2] = nowLine
								} else {
									this.polyline[1] = nowLine
								}
								this.polyline = [...this.polyline] //需要解构视图才会更新
								// 传递上一次坐标与当前坐标  计算差值
								let temp = this.getMapDistance(this.markers[this.numid-2].latitude, this.markers[this.numid-2].longitude, this.markers[this.numid-1].latitude,this.markers[this.numid-1].longitude)
								let tempall = Number(this.distanceNum) + Number(temp)
								this.distanceNum = tempall.toFixed(3)
							}
					  }
					});
				},5000)
			},
      //计时事件
			TimeConver(startTime){
				let that = this
				let time = startTime.split(',')
				 set = setInterval(function() {
					time[2]++
					if(time[2] <10){
						time[2]= "0"+time[2]
					}else if(time[2] >60){
						time[1]++
						time[2] = "00"
						if(time[1] <10){
							time[1]= "0"+time[1] 
						}else if(time[1] >60){
							time[1]="00"
							time[0]++
						}
					}
					var v = time.join(':')
					that.Nowtime = v
				},1000)
			},
      // 根据获取坐标定位中心点
			toLocation(lng, lat) {
				let mapCtx = uni.createMapContext('map', this)
				// 改变地图中心位置
			 	mapCtx.moveToLocation({
					longitude: lng,
					latitude: lat,
					success: (res) => {
						// console.log('改变地图中心位置');
					},
				})
			},
			// 计算距离 
			getMapDistance(lat1, lng1, lat2, lng2) {
				var radLat1 = this.distance(lat1);
				var radLat2 = this.distance(lat2);
				var a = radLat1 - radLat2;
				var b = this.distance(lng1) - this.distance(lng2);
				var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)))
				s = s * 6378.137; // EARTH_RADIUS;
				s = Math.round(s * 10000) / 10000 //输出为公里
				// s = s / 1000
				var r = s.toFixed(3)

				return r;
			},
      // 将角度换算为弧度
			distance(d) {
        return d * Math.PI / 180.0;
			},
      // 返回
      backPage() {
        let that = this
        if(!that.startBtn) {
          uni.showModal({
            title: '提示',
            content: '是否退出巡查？',
            success: function (res) {
              if(res.confirm) {
                that.$request.delectreseId({ reseId: that.patrolinfo.rese_id }).then(resp => {
                  if(resp.code == 200) {
                    setTimeout(() => {
                      uni.navigateBack();
                    }, 10);
                  }
                })
              } else if (res.cancel) {
                console.log('用户点击取消');
              }
            }
          });
          return true
        } else {
          setTimeout(() => {
            uni.navigateBack();
          }, 10);
        }
      },
      // 跳转详情页面
      toPage() {
        if(this.baseinfo.detailsId) {
          // uni.navigateTo({ url: './detail?rese_id=' + this.patrolinfo.rese_id + '&part_id=' + this.patrolinfo.part_id })
          uni.navigateTo({ url: './detail?detailsId=' + this.baseinfo.detailsId })
        } else {
          uni.showToast({
            title: '请开启巡查后查看检查详情',
            icon: 'none',
            duration: 2000
          });
        }
      },
    },
    onBackPress(e) {
      if(e.from == 'backbutton' && !this.startBtn) {
        this.backPage()
        return true
      }
		}, 
  }
</script>

<style lang="scss" scoped>
  .top_map {
    width: 100%;
    height: 50vh;
  }

  .operate {
    margin: 20rpx 30rpx 0;
    background-color: #fff;
    border-top-left-radius: 40rpx;
    border-top-right-radius: 40rpx;
    height: calc(50vh - 20rpx);
    padding: 0 55rpx;
    box-shadow: 0 0 5px rgba($color: #000000, $alpha: 0.2);
    position: relative;

    .backbtn {
      width: 56rpx;
      height: 56rpx;
      position: absolute;
      top: 20rpx;
      left: 20rpx;

      image {
        width: 100%;
        height: 100%;
      }
    }

    .operate_top {
      text-align: center;
      padding: 50rpx 0;
      border-bottom: 2px solid #afafb0;

      view {
        font-size: 40rpx;
        line-height: 40rpx;
        color: #000;
      }
    }

    .operate_bot {
      display: flex;
      align-items: center;
      flex-wrap: wrap;

      .operate_list {
        width: 33.33%;
        text-align: center;
        font-size: 28rpx;
        line-height: 28rpx;
        padding-top: 70rpx;

        .operate_list_title {
          color: #969696;
        }
        .operate_list_info {
          padding-top: 70rpx;
          color: #000;
        }
      }
    }

    .operate_tips {
      font-size: 24rpx;
      line-height: 24rpx;
      text-align: center;
      padding-top: 60rpx;
      color: #ababac;
    }

    .operate_btn {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-top: 40rpx;

      .operateBtn {
        width: 45%;
        font-size: 32rpx;
        line-height: 32rpx;
        padding: 30rpx 0;
        color: #fff;
        background: linear-gradient(to right, #8dbffc, #3d7bfc);
        text-align: center;
        border-radius: 80rpx;

        &.stop {
          background: linear-gradient(to right, #f8aa9d, #f36363);
        }
      }
    }
  }
</style>
